<template>
    <section>
        <full-screen-dialog
            :title="titleMap[mode]"
            v-model="visible"
            :width="1500"
            destroy-on-close
            @closed="$emit('closed')"
        >
            <el-form ref="dialogForm" label-width="100px">
                <el-form inline label-width="49px" :model="entityObj" style="margin-top: 5px">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="对账日期" label-width="100px" style="width: 100%;">
                                <el-date-picker
                                    @change="changeStorageOrderAccountTimes"
                                    style="width: 100%;"
                                    v-model="entityObj.storageOrderAccountTimes"
                                    type="datetimerange"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    format="YYYY-MM-DD HH:mm:ss"
                                    range-separator="-"
                                    unlink-panels="true"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    :default-time="defaultTime"
                                    required
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="供应商" label-width="100px" style="width: 100%;">
                                <sc-supplier-select
                                    ref="supplierSelect"
                                    :props="supplierProps"
                                    queryType="purchase-unity-supplier-relation/pages"
                                    :selectKeyValue="'key'"
                                    :multiple="false"
                                    v-if="orgType==1"
                                    v-model="entityObj.supplier"
                                    @fatherMethod="supplierSelectProcess"
                                    style="width: 100%;"
                                ></sc-supplier-select>
                                <el-input
                                    placeholder="---供应商---"
                                    v-if="orgType==3"
                                    disabled
                                    v-model="entityObj.supplierName"
                                    style="width: 100%;"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="申请人" label-width="100px" style="width: 100%;">
                                <el-input
                                    placeholder="---请输入申请人---"
                                    v-model="entityObj.ApplicantUser"
                                    style="width: 100%;"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="联系电话" label-width="100px" style="width: 100%;">
                                <el-input
                                    placeholder="---请输入联系电话---"
                                    v-model="entityObj.Tel"
                                    style="width: 100%;"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                label="对账单位"
                                prop="purchaseUnityId"
                                label-width="100px"
                                v-if="orgType==3"
                                style="width: 100%;"
                            >
                                <el-select
                                    @change="purchaseUnityChange"
                                    class="w-300"
                                    placeholder="---请选择对账单位---"
                                    v-model="entityObj.purchaseUnityId"
                                    style="width: 100%;"
                                >
                                    <el-option
                                        v-for="item in optionsPurchaseUnity"
                                        :key="item.purchaseUnityId"
                                        :label="item.purchaseUnityName"
                                        :value="item.purchaseUnityId"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item
                                label="对账单位"
                                prop="purchaseUnityId"
                                label-width="100px"
                                v-if="orgType==1"
                                style="width: 100%;"
                            >
                                <el-input
                                    placeholder="---请输入对账单位名称---"
                                    v-model="entityObj.purchaseUnityName"
                                    style="width: 100%;"
                                    disabled
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label-width="100px" label="附件上传" style="width: 100%;">
                                <sc-upload-file
                                    v-model="entityObj.accountFile"
                                    :objName="'Supply/giveOrder'"
                                    draggable
                                    :uploadType="'OSS'"
                                    :bucketName="'jtmc'"
                                    :limit="1"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="备注" label-width="100px" style="width: 100%;">
                                <el-input
                                    placeholder="---请输入一些对账的要求---"
                                    v-model="entityObj.Remarks"
                                    type="textarea"
                                    style="width: 100%;"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div style="margin-bottom: 10px;">
                    <el-button type="primary" @click="opDelBatch()">批量删除</el-button>
                    <el-button type="primary" @click="choiceReceive()">选择对账数据</el-button>
                </div>
                <scTable
                    :data="entityList"
                    bindType="bindEntity"
                    :border="true"
                    :isKeyDown="false"
                    style="width: 100%"
                    show-summary
                    @selection-change="selectionChange"
                    :row-class-name="setRowClass"
                    :span-method="objectSpanMethod"
                >
                    <el-table-column type="selection" width="50"></el-table-column>
                    <el-table-column label="序号" type="index" width="80"></el-table-column>
                    <el-table-column
                        label="对账状态"
                        prop="supplierStatusDesc"
                        width="100"
                        v-if="orgType==1"
                    ></el-table-column>
                    <el-table-column
                        label="对账状态"
                        prop="wineStatusDesc"
                        width="100"
                        v-if="orgType==3"
                    ></el-table-column>
                    <el-table-column label="业务日期" prop="applyDate" width="200"></el-table-column>
                    <el-table-column
                        label="单据编号"
                        prop="storageOrderCode"
                        width="200"
                        v-if="orgType==1"
                    ></el-table-column>
                    <el-table-column label="类型" prop="storageOrderTypeDesc" width="100"></el-table-column>
                    <el-table-column label="门店" prop="storeName" width="200"></el-table-column>
                    <el-table-column label="采购单号" prop="purchaseOrderCode" width="200"></el-table-column>
                    <el-table-column label="物料编码" prop="materialCode" width="100"></el-table-column>
                    <el-table-column label="物料名称" prop="materialName" width="250"></el-table-column>
                    <el-table-column label="规格型号" prop="materialSpecs" width="100"></el-table-column>
                    <el-table-column label="数量" prop="purchaseQty" width="100"></el-table-column>
                    <el-table-column label="单位" prop="unitName" width="100"></el-table-column>
                    <el-table-column label="单价" prop="purchasePrice" width="100"></el-table-column>
                    <el-table-column label="金额" prop="purchaseTotalAmount" width="100"></el-table-column>
                    <el-table-column label="业务员" prop="salesman" width="100" v-if="orgType==1"></el-table-column>
                    <el-table-column label="制单人" prop="documentsUser" width="100" v-if="orgType==1"></el-table-column>
                    <el-table-column label="操作" fixed="right" align="center" width="100">
                        <template #default="scope">
                            <el-button-group>
                                <el-button
                                    text
                                    type="primary"
                                    size="small"
                                    @click="opDel(scope.row, scope.$index)"
                                >删除</el-button>
                            </el-button-group>
                        </template>
                    </el-table-column>
                </scTable>
            </el-form>

            <template #footer>
                <div style="text-align: center;">
                    <el-button @click="visible = false">关 闭</el-button>
                    <el-button type="primary" @click="submit()" v-if="mode == 'Send'">确认发送对账申请</el-button>
                    <el-button type="primary" @click="submit()" v-if="mode == 'Edit'">确认修改对账申请</el-button>
                </div>
            </template>
        </full-screen-dialog>

        <receive-choice
            v-if="visibleReceiveChoice"
            ref="receiveChoiceObj"
            @fatherMethod="opBindData"
            @checkTable="checkTable"
            @success="handleSaveSuccess"
            @closed="visibleReceiveChoice = false"
        ></receive-choice>

        <!--未对账弹窗-->
        <el-dialog title="提示" width="1200px" v-model="unCheckDialog">
            <div
                style="font-size: 16px;text-align: center;color: red;margin: 10px;"
            >{{unCheckDialogTip}}</div>
            <el-date-picker
                style="width: 300px"
                v-model="unCheckQuery.applyDate"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                range-separator="-"
                unlink-panels="true"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="defaultTime"
            />&nbsp;
            <el-input
                placeholder="---请输入物料编码---"
                v-model="unCheckQuery.materialCode"
                style="width: 180px"
            />&nbsp;
            <el-input
                placeholder="---请输入物料名称---"
                v-model="unCheckQuery.materialName"
                style="width: 180px"
            />&nbsp;
            <el-button type="primary" @click="unCheckSeach">查询</el-button>
            <el-table
                :data="unCheckItemResults"
                style="width: 100%"
                max-height="450"
                @selection-change="unCheckSelectionChange"
            >
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column label="业务时间" prop="applyDate" min-width="120">
                    <template #default="scope">
                        {{scope.row.applyDate&&scope.row.applyDate.length>10? scope.row.applyDate.slice(0, 10):scope.row.applyDate}}
                    </template>
                </el-table-column>
                <el-table-column label="采购入库单" prop="storageOrderCode" min-width="200"></el-table-column>
                <el-table-column label="供应商" prop="supplierName" min-width="120"></el-table-column>
                <el-table-column label="采购单号" prop="purchaseOrderCode" min-width="180"></el-table-column>
                <el-table-column label="物料编码" prop="materialCode" min-width="100"></el-table-column>
                <el-table-column label="物料名称" prop="materialName" min-width="230"></el-table-column>
                <el-table-column label="规格型号" prop="materialSpecs" min-width="100"></el-table-column>
                <el-table-column label="数量" prop="purchaseQty" min-width="100"></el-table-column>
                <el-table-column label="单位" prop="unitName" min-width="100"></el-table-column>
                <el-table-column label="单价" prop="purchasePrice" min-width="100"></el-table-column>
                <el-table-column label="金额" prop="purchaseTotalAmount" min-width="100"></el-table-column>
            </el-table>
            <template #footer>
                <div style="text-align: center;">
                    <el-button @click="unCheckDialog = false">取消</el-button>
                    <el-button type="primary" @click="unCheckAdd()">确定添加</el-button>
                    <el-button type="warning" @click="confirmSendAccountData()">发送账单</el-button>
                </div>
            </template>
        </el-dialog>
    </section>
</template>

<script>
import { ElStep } from "element-plus";
import receiveChoice from "./receiveChoice";
import tool from "@/utils/tool";
export default {
    components: {
        receiveChoice,
    },
    emits: ["success", "closed"],
    data() {
        return {
            orgType: 3,
            mode: "Send",
            titleMap: {
                Send: "发送对账申请",
                Edit: "修改对账申请",
            },
            visibleReceiveChoice: false, //采购单窗体
            visible: false,
            supName: "",
            entityModal: {},
            entityList: [],
            selectionRows: [],
            optionsPurchaseUnity: [],
            supplierProps: {
                label: "supplierName",
                value: "supplierId",
            },
            entityObj: {
                storageOrderAccountId: 0,
                supplierId: 0,
                supplierName: "",
                accountFile: "",
                storageOrderAccountTimes: [],
                StorageOrderItemId: "",
                Remarks: "",
                purchaseUnityId: "",
            },
            defaultTime: [
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ],
            unCheckDialog: false, //未对账弹窗
            unCheckDialogTip: "", //未对账提示
            unCheckItems: [],
            unCheckSelectionRows: [],
            unCheckQuery: {},
        };
    },
    methods: {
        purchaseUnityChange() {
            this.entityList = [];
        },
        choiceReceive() {
            if (
                !this.entityObj.storageOrderAccountTimes ||
                this.entityObj.storageOrderAccountTimes.length == 0
            ) {
                this.$message.error("请选择对账时间");
                return;
            }
            if (!this.entityObj.purchaseUnityId) {
                this.$message.error("请选择对账单位");
                return;
            }

            if (!this.entityObj.supplierId) {
                this.$message.error("请选择对账单位");
                return;
            }

            const notStorageOrderIds = this.entityList.map(
                (p) => p.storageOrderId
            );

            this.visibleReceiveChoice = true;
            this.$nextTick(() => {
                this.$refs.receiveChoiceObj.initData(
                    this.entityObj.purchaseUnityId,
                    this.entityObj.storageOrderAccountTimes,
                    this.entityObj.supplierId,
                    notStorageOrderIds,
                    this.entityObj.supplierOrgType
                );
            });
        },
        open(mode = "Send") {
            this.mode = mode;
            this.visible = true;
            // this.entityList = []
            return this;
        },
        checkTable(data) {
            console.log("selected", data);
            this.entityList.push(...data);
        },
        changeStorageOrderAccountTimes() {
            this.entityList = [];
        },
        async setData(data, mode) {
            try {
                let arr = [];
                if (mode == "Edit") {
                    this.entityObj.storageOrderAccountId =
                        data.storageOrderAccountId;
                    this.entityObj.supplierId = data.supplierId;
                    this.entityObj.supplierName = data.supplierName;
                    this.entityObj.storageOrderAccountTimes.push(
                        data.accountStartDate
                    );
                    this.entityObj.storageOrderAccountTimes.push(
                        data.accountEndDate
                    );
                    this.entityObj.accountFile = data.accountFile;
                    this.entityObj.ApplicantUser = data.applicantUser;
                    this.entityObj.Tel = data.tel;
                    this.entityObj.Remarks = data.remarks;
                    this.entityObj.purchaseUnityId = data.purchaseUnityId;
                    let arr = [];
                    arr.push(data.storageOrderAccountId);
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                "storage-order-account/items",
                                {
                                    storageOrderAccountIds: arr,
                                }
                            );
                        if (returnValue.status == 200) {
                            this.visible = true;
                            console.log(returnValue.response);
                            this.entityList = returnValue.response;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                        }
                    } catch (error) {
                        this.loading = false;
                        return false;
                    }
                } else {
                    //this.entityObj.supplierName = data;
                    this.entityObj.ApplicantUser =
                        tool.data.get("USER_INFO").Name;
                    this.entityObj.Tel = tool.data.get("USER_INFO").Mobile;
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        // 删除
        opDel(row, index) {
            this.entityList.splice(index, 1);
        },
        // 批量删除
        opDelBatch() {
            if (this.selectionRows.length > 0) {
                this.selectionRows.forEach((row) => {
                    this.entityList.splice(this.entityList.indexOf(row), 1);
                });
            } else {
                this.$message.error("请选择要删除的数据");
            }
        },
        delAll() {
            if (this.selectionRows.length > 0) {
                console.log(this.selectionRows);
                const smallSet = new Set(
                    this.selectionRows.map((item) => item.storageOrderCode)
                );
                this.entityList = this.entityList.filter(
                    (item) => !smallSet.has(item.storageOrderCode)
                );
            } else {
                this.$message.error("请选择要删除的数据");
            }
        },
        setRowClass({ row }) {
            if (this.selectionRows.includes(row)) {
                return "selected-row-color";
            }
            return "";
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
        },
        async submit() {
            // if (this.selectionRows.length > 0) {

            // 	if (this.entityObj.storageOrderAccountTimes.length <= 0) {

            // 		this.$message.error("请选择对账日期");
            // 		return
            // 	}
            // 	// 将选中的数据的 storageOrderCode 转换为一个集合（用于快速查找）
            // 	const smallSet = new Set(this.selectionRows.map(item => item.storageOrderCode));
            // 	// 使用 filter 方法遍历表格数据，筛选符合条件的对象
            // 	const resultArray = this.entityList.filter(item => smallSet.has(item.storageOrderCode));
            // 	// 定义要保留的属性列表
            // 	const desiredProperties = ["storageOrderId", "storageOrderCode"];
            // 	let filteredArray = resultArray.map(obj => {
            // 		// 使用解构赋值和对象字面量来过滤不需要的属性
            // 		let filteredObj = {};
            // 		desiredProperties.forEach(prop => {
            // 			filteredObj[prop] = obj[prop];
            // 		});
            // 		return filteredObj;
            // 	});
            // 	this.entityObj.storageOrderAccountItems = filteredArray

            // 	const returnValue = await this.$API.auth.PostProcessApi.post("storage-order-account/send", this
            // 		.entityObj);
            // 	if (returnValue.status == 200) {
            // 		this.$message.success(returnValue.msg);
            // 		this.$emit("fatherMethod");
            // 		this.visible = false;
            // 	} else {
            // 		this.$message.error("操作失败:" + returnValue.msg);
            // 	}
            // } else {
            // 	this.$message.error("请选择要发送对账申请的数据");
            // }
            if (
                !this.entityObj.storageOrderAccountTimes ||
                this.entityObj.storageOrderAccountTimes.length == 0
            ) {
                this.$message.error("请选择对账时间");
                return;
            }
            if (!this.entityObj.purchaseUnityId) {
                this.$message.error("请选择对账单位");
                return;
            }
            if (!this.entityList.length > 0) {
                this.$message.error("请选择对账数据");
                return;
            }
            this.entityObj.storageOrderAccountItems = this.entityList;
            try {
                var lastresponse = await this.$API.auth.PostProcessApi.post(
                    "storage-order/isLastAccount",
                    this.entityObj
                );
                if (lastresponse.status == 200) {
                    if (!lastresponse.response.success) {
                        this.unCheckDialog = true;
                        this.unCheckDialogTip =
                            lastresponse.response.msg + ",是否继续?";
                        this.unCheckItems = lastresponse.response.unChecks;
                        this.unCheckSeach();
                        // this.$confirm(
                        //     lastresponse.response.msg + ",是否继续?",
                        //     "提示",
                        //     {
                        //         confirmButtonText: "确定",
                        //         cancelButtonText: "取消",
                        //         type: "warning",
                        //     }
                        // ).then(async () => {
                        //     // console.log('发生至门店modal：',this.entityObj)
                        //     const returnValue =
                        //         await this.$API.auth.PostProcessApi.post(
                        //             "storage-order-account/send",
                        //             this.entityObj
                        //         );
                        //     if (returnValue.status == 200) {
                        //         this.$message.success(returnValue.msg);
                        //         this.$emit("fatherMethod");
                        //         this.visible = false;
                        //     } else {
                        //         this.$message.error(
                        //             "操作失败:" + returnValue.msg
                        //         );
                        //     }
                        // });
                    } else {
                        const returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                "storage-order-account/send",
                                this.entityObj
                            );
                        if (returnValue.status == 200) {
                            this.$message.success(returnValue.msg);
                            this.$emit("fatherMethod");
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                        }
                    }
                } else {
                    this.$message.error("操作失败:" + lastresponse.msg);
                }
            } catch (error) {
                this.loading = false;
                this.$message.error(error.message);
                return false;
            }
            // if (this.entityObj.storageOrderAccountTimes.length <= 0) {

            // 	this.$message.error("请选择对账日期");
            // 	return
            // }
        },
        //未对账查询
        unCheckSeach() {
            this.unCheckItemResults = this.unCheckItems;
            if (this.unCheckQuery.applyDate) {
                console.log("applyDate", this.unCheckQuery.applyDate);
                this.unCheckItemResults = this.unCheckItemResults.filter(
                    (p) =>
                        p.applyDate >= this.unCheckQuery.applyDate[0] &&
                        p.applyDate <= this.unCheckQuery.applyDate[1]
                );
            }

            if (this.unCheckQuery.materialCode) {
                this.unCheckItemResults = this.unCheckItemResults.filter((p) =>
                    p.materialCode.includes(this.unCheckQuery.materialCode)
                );
            }

            if (this.unCheckQuery.materialName) {
                this.unCheckItemResults = this.unCheckItemResults.filter((p) =>
                    p.materialName.includes(this.unCheckQuery.materialName)
                );
            }
        },
        unCheckSelectionChange(selection) {
            this.unCheckSelectionRows = selection;
        },
        //选择未对账数据添加
        async unCheckAdd() {
            if (this.unCheckSelectionRows.length > 0) {
                this.unCheckSelectionRows.forEach((row) => {
                    this.entityList.push(row);
                });
                this.unCheckDialog = false;
            } else {
                this.$message.error("请选择要添加的数据");
            }
        },
        //确定发送对账数据
        async confirmSendAccountData() {
            console.log("发生至门店modal：", this.entityObj);
            const returnValue = await this.$API.auth.PostProcessApi.post(
                "storage-order-account/send",
                this.entityObj
            );
            if (returnValue.status == 200) {
                this.$message.success(returnValue.msg);
                this.$emit("fatherMethod");
                this.visible = false;
            } else {
                this.$message.error("操作失败:" + returnValue.msg);
            }
        },
        //获取供应商
        async supplierSelectProcess(rowData) {
            this.entityObj.supplier = {
                supplierOrgType: rowData.supplierOrgType,
                supplierId: rowData.supplierId,
                supplierName: rowData.supplierName,
            };
            this.entityObj.supplierOrgType = rowData.supplierOrgType;
            this.entityObj.supplierId = rowData.supplierId;
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {},
    },
    async mounted() {
        this.orgType = tool.data.get("USER_INFO").AccountType;
        if (this.orgType == 1) {
            this.entityObj.purchaseUnityId = tool.data.get("USER_INFO").OrgId;
            this.entityObj.purchaseUnityName =
                tool.data.get("USER_INFO").OrgName;
        } else {
            this.entityObj.supplierId = tool.data.get("USER_INFO").OrgId;
            this.entityObj.supplierName = tool.data.get("USER_INFO").OrgName;
            //获取回收单位
            try {
                const returnStatus = await this.$API.auth.GetProcessApi.get(
                    "purchase-unity/list"
                );
                if (returnStatus.status == 200) {
                    this.optionsPurchaseUnity = returnStatus.response;
                } else {
                    this.$message.error("操作失败:" + returnStatus.msg);
                }
            } catch (error) {
                this.$message.error(error.message);
            }
        }

        console.log("entityObj", this.entityObj);
    },
};
</script>

<style lang="scss" scoped>
/* 当表格行处于悬停状态时改变背景颜色 */
::v-deep .el-table .el-table__row:hover {
    background-color: #dae8f7;
}
::v-deep .el-table__body .el-table__row--striped.hover-row td {
    background-color: #dae8f7 !important;
}
//   斑马纹选中颜色
::v-deep .el-table__body .el-table__row--striped.selected-row-color td {
    background-color: #b8dcff !important;
}
::v-deep .el-table {
    --el-table-row-hover-bg-color: #dae8f7;
}

::v-deep .el-table tr:nth-child(2n) {
    background: #f2f2f2;
}
</style>
<style>
.el-table .selected-row-color {
    background-color: #b8dcff !important;
}
.el-table--enable-row-hover .el-table__body tr.selected-row-color:hover > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper .el-table__body tr.selected-row-color.hover-row > td {
    background-color: #b8dcff !important;
}
.el-table__fixed-body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > .el-table__row--striped {
    background-color: #b8dcff !important;
}
</style>
